import com.alibaba.fastjson.JSON;
import com.share.bean.GoodVO;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * author:caifan
 * date:2020/1/7
 */
public class ObjectType {

    public static void main(String[] args) throws Exception {
        GoodVO goodVO = new GoodVO();
        goodVO.setPrice(new BigDecimal(3.324));
        goodVO.setTaxRate(new BigDecimal(0.1326));
        goodVO.setTax(new BigDecimal(1.342));
        goodVO.setProductTime(new Date());
        scale(goodVO);
        System.out.println(goodVO.toString());
    }

    public static void scale(Object obj) throws Exception {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor.getPropertyType().getSimpleName().equals(BigDecimal.class.getSimpleName())) {
                Object value = propertyDescriptor.getReadMethod().invoke(obj);
                if (!Objects.isNull(value)) {
                    propertyDescriptor.getWriteMethod().invoke(obj, new BigDecimal(String.valueOf(value)).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            }
        }
    }

    @Test
    public void decimalTest() throws Exception {
        String price = "1.224";
        System.out.println(new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_EVEN));
        HeadReq headReq = new HeadReq();
        headReq.setTotalPrice(new BigDecimal(2.3633));
        List<LineReq> lineReqs = new ArrayList<>();
        LineReq lineReq1 = new LineReq();
        LineReq lineReq2 = new LineReq();
        lineReq1.setPrice(new BigDecimal(1.452));
        lineReq2.setPrice(new BigDecimal(2.336));
        lineReqs.add(lineReq1);
        lineReqs.add(lineReq2);
        RequestReq requestReq = new RequestReq();
        requestReq.setHeadReq(headReq);
        requestReq.setLineReqList(lineReqs);

        scale(headReq);
        for (LineReq line : lineReqs) {
            scale(line);
        }
        System.out.println(JSON.toJSONString(requestReq));
    }


    @Setter
    @Getter
    class RequestReq {
        HeadReq headReq;
        List<LineReq> lineReqList;
    }

    @Getter
    @Setter
    class HeadReq {
        BigDecimal totalPrice;
    }

    @Getter
    @Setter
    class LineReq {

        private BigDecimal price;
    }
}
